﻿<%@ WebHandler Language="C#" Class="ApsResourceCapacityHandler" %>

//Description:设备甘特图
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:Wangjh
//create Date:2022-06-28
using System;
using System.Web;
using BusinessRule.DTO;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Web.SessionState;
using System.Data;

public class ApsResourceCapacityHandler : IHttpHandler,IRequiresSessionState {
    private LimitedCapacityBusiness m_LMObj = new LimitedCapacityBusiness();
    private ZSLimitedCapacityBusiness zs_LMObj = new ZSLimitedCapacityBusiness();
    CurrentUserInfo m_UserInfo;
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            switch (action)
            {
                case "getResourceApsGrid":
                    GetResourceApsGrid(context);
                    break;
                case "getResourceApsForGrant":
                    GetResourceApsForGrant(context);
                    break;
                case "getEmployeeApsForGrant":
                    GetEmployeeApsForGrant(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception e)
        {
            var result = new uMESProcessResult()
            {
                Result = false,
                Message = e.Message
            };
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }
    public bool IsReusable {
        get {
            return false;
        }
    }

    /// <summary>
    /// 获取设备的排产计划,甘特图用
    /// </summary>
    /// <param name="context"></param>
    public void GetEmployeeApsForGrant(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        Dictionary<string, string> para = new Dictionary<string, string>();

        if (context.Request["factoryID"] != null && !string.IsNullOrWhiteSpace(context.Request["factoryID"].ToString()))
        {
            para.Add("FactoryID", context.Request["factoryID"].ToString());
        }
        if (context.Request["workcenterID"] != null && !string.IsNullOrWhiteSpace(context.Request["workcenterID"].ToString()))
        {
            para.Add("WorkcenterID", context.Request["workcenterID"].ToString());
        }
        if (context.Request["teamID"] != null && !string.IsNullOrWhiteSpace(context.Request["teamID"].ToString()))
        {
            para.Add("teamID", context.Request["workcenterID"].ToString());
        }
        if (context.Request["startDate"] != null && !string.IsNullOrWhiteSpace(context.Request["startDate"].ToString()))
        {
            para.Add("StartDate", context.Request["startDate"].ToString());
        }
        else
        {
            //星期一为第一天  
            int weeknow = Convert.ToInt32(DateTime.Now.DayOfWeek);
            //因为是以星期一为第一天，所以要判断weeknow等于0时，要向前推6天。  
            weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
            int daydiff = (-1) * weeknow;

            //para["StartDate"] = DateTime.Now.AddDays(weeknow).ToString("yyyy/MM/dd HH:mm:ss");
            //para["StartDate"] = "2022/5/7 6:00:00";
        }
        if (context.Request["endDate"] != null && !string.IsNullOrWhiteSpace(context.Request["endDate"].ToString()))
        {
            para.Add("EndDate", context.Request["endDate"].ToString());
        }
        else
        {
            //星期天为最后一天  
            int weeknow = Convert.ToInt32(DateTime.Now.DayOfWeek);
            weeknow = (weeknow == 0 ? 7 : weeknow);
            int daydiff = (7 - weeknow);

            // para["EndDate"] = DateTime.Now.AddDays(daydiff+7).ToString("yyyy-MM-dd");
            //para["EndDate"] = "2022/5/20 6:00:00";
        }

        //para["ResourceIds"] = "'0005d2800000002e'";

        para.Add("Status", "1");
        DataTable dt = m_LMObj.GetEmpApsDataForGrant(para);

        //排产数据格式化
        List<Dictionary<string, object>> returnData = new List<Dictionary<string, object>>();
        DataTable resDt = dt.DefaultView.ToTable(true, "employeeid", "fullname");

        foreach (DataRow resRow in resDt.Rows)
        {
            Dictionary<string, object> resApsData = new Dictionary<string, object>();
            resApsData.Add("id", resRow["employeeid"].ToString());
            resApsData.Add("name", resRow["fullname"].ToString());

            var _resAps = dt.Select("employeeid='" + resRow["employeeid"].ToString() + "'");

            List<Dictionary<string, object>> periods = new List<Dictionary<string, object>>();
            Dictionary<string, object> period = new Dictionary<string, object>();

            List<string> colorList = new List<string>() { "#DC143C", "#FFFF00", "#0000FF" };
            int lastColorIndex = 0; string lastApsplandetailiId = "";

            foreach (DataRow resAps in _resAps)
            {
                period = new Dictionary<string, object>();

                if (lastApsplandetailiId == resAps["apsplandetailid"].ToString())
                {

                }
                else
                {
                    lastApsplandetailiId = resAps["apsplandetailid"].ToString();
                    lastColorIndex++;
                    if (lastColorIndex > colorList.Count - 1)
                    {
                        lastColorIndex = 0;
                    }
                }

                period["id"] = Guid.NewGuid().ToString();
                period["text"] = "";
                period["start"] = resAps["stepstart"].ToString();
                period["end"] = resAps["stepend"].ToString();
                period["fill"] = colorList[lastColorIndex];

                //个性化属性
                var customData = new Dictionary<string, object>();
                customData["stepstarthms"] = resAps["stepstarthms"].ToString();
                customData["stependhms"] = resAps["stependhms"].ToString();
                var ratio = (DateTime.Parse(resAps["stependhms"].ToString()) - DateTime.Parse(resAps["stepstarthms"].ToString())).TotalMinutes;
                customData["ratio"] = Math.Round((ratio / (24 * 60)), 2);//高度占用比
                ratio = (DateTime.Parse(resAps["stepstarthms"].ToString()) - DateTime.Parse(resAps["stepstarthms"].ToString()).Date).TotalMinutes;
                customData["startPercent"] = Math.Round((ratio / (24 * 60)), 2);//起始位置比
                customData["containername"] = resAps["containername"].ToString();
                customData["workflowstepname"] = resAps["workflowstepname"].ToString();
                customData["resourceid"] = resAps["resourceid"].ToString();
                period["customData"] = customData;

                periods.Add(period);
            }

            resApsData["periods"] = periods;

            returnData.Add(resApsData);
        }

        result.ReturnData = JsonConvert.SerializeObject(returnData);
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取设备详细排产信息
    /// </summary>
    /// <param name="context"></param>
    public void GetResourceApsGrid(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        Dictionary<string, string> para = new Dictionary<string, string>();

        if (context.Request["resourceId"] != null && !string.IsNullOrWhiteSpace(context.Request["resourceId"].ToString()))
        {
            para.Add("ResourceID", context.Request["resourceId"].ToString());
        }
        if (context.Request["containDate"] != null && !string.IsNullOrWhiteSpace(context.Request["containDate"].ToString()))
        {
            para.Add("ContainDate", context.Request["containDate"].ToString());
        }
        if (context.Request["startDate"] != null && !string.IsNullOrWhiteSpace(context.Request["startDate"].ToString()))
        {
            para.Add("StartDate", context.Request["startDate"].ToString());
        }
        if (context.Request["endDate"] != null && !string.IsNullOrWhiteSpace(context.Request["endDate"].ToString()))
        {
            para.Add("EndDate", context.Request["endDate"].ToString());
        }

        para.Add("Status","1");

        DataTable dt = m_LMObj.GetStepLMAps2(para);
        
        result.DBTable = dt;
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    
    /// <summary>
    /// 获取设备的排产计划,甘特图用
    /// </summary>
    /// <param name="context"></param>
    public void GetResourceApsForGrant(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        uMESProcessResult result = new uMESProcessResult();
        result.Result = false;

        Dictionary<string, string> para = new Dictionary<string, string>();

        if (context.Request["factoryID"] !=null&& !string.IsNullOrWhiteSpace(context.Request["factoryID"].ToString()))
        {
            para.Add("FactoryID", context.Request["factoryID"].ToString());
        }
        if (context.Request["workcenterID"] != null && !string.IsNullOrWhiteSpace(context.Request["workcenterID"].ToString()))
        {
            para.Add("WorkcenterID", context.Request["workcenterID"].ToString());
        }
        if (context.Request["teamID"] != null && !string.IsNullOrWhiteSpace(context.Request["teamID"].ToString()))
        {
            para.Add("teamID", context.Request["workcenterID"].ToString());
        }
        if (context.Request["startDate"] != null && !string.IsNullOrWhiteSpace(context.Request["startDate"].ToString()))
        {
            para.Add("StartDate", context.Request["startDate"].ToString());
        }
        else {
            //星期一为第一天  
            int weeknow = Convert.ToInt32(DateTime.Now .DayOfWeek);
            //因为是以星期一为第一天，所以要判断weeknow等于0时，要向前推6天。  
            weeknow = (weeknow == 0 ? (7 - 1) : (weeknow - 1));
            int daydiff = (-1) * weeknow;

            //para["StartDate"] = DateTime.Now.AddDays(weeknow).ToString("yyyy/MM/dd HH:mm:ss");
            //para["StartDate"] = "2022/5/7 6:00:00";
        }
        if (context.Request["endDate"] != null && !string.IsNullOrWhiteSpace(context.Request["endDate"].ToString()))
        {
            para.Add("EndDate", context.Request["endDate"].ToString());
        }
        else {
            //星期天为最后一天  
            int weeknow = Convert.ToInt32(DateTime.Now.DayOfWeek);
            weeknow = (weeknow == 0 ? 7 : weeknow);
            int daydiff = (7 - weeknow);

           // para["EndDate"] = DateTime.Now.AddDays(daydiff+7).ToString("yyyy-MM-dd");
            //para["EndDate"] = "2022/5/20 6:00:00";
        }

        //para["ResourceIds"] = "'0005d2800000002e'";

        para.Add("Status", "1");
        DataTable dt=new DataTable();
        if (m_UserInfo.FactoryCode == "603")
            dt = zs_LMObj.GetResApsDataForGrant(para);
        else
            dt = m_LMObj.GetResApsDataForGrant(para);

        //排产数据格式化
        List<Dictionary<string, object>> returnData = new List<Dictionary<string, object>>();
        DataTable resDt = dt.DefaultView.ToTable(true, "resourceid", "RESNAME");

        foreach (DataRow resRow in resDt.Rows) {
            Dictionary<string, object> resApsData = new Dictionary<string, object>();
            resApsData.Add("id", resRow["resourceid"].ToString());
            resApsData.Add("name", resRow["RESNAME"].ToString());

            var _resAps = dt.Select("resourceid='" + resRow["resourceid"].ToString() + "'");

            List<Dictionary<string, object>> periods = new List<Dictionary<string, object>>();
            Dictionary<string, object> period = new Dictionary<string, object>();

            List<string> colorList = new List<string>() { "#DC143C", "#FFFF00", "#0000FF" };
            int lastColorIndex = 0; string lastApsplandetailiId = "";
            
            foreach (DataRow resAps in _resAps) {
                period = new Dictionary<string, object>();

                if (lastApsplandetailiId == resAps["apsplandetailid"].ToString())
                {

                }
                else
                {
                    lastApsplandetailiId = resAps["apsplandetailid"].ToString();
                    lastColorIndex++;
                    if (lastColorIndex > colorList.Count-1) {
                        lastColorIndex = 0;
                    }               
                }
                
                period["id"] = Guid .NewGuid().ToString ();
                period["text"] = "";
                period["start"] = resAps["stepstart"].ToString();
                period["end"] = resAps["stepend"].ToString();
                period["fill"] = colorList[lastColorIndex];                               

                //个性化属性
                var customData = new Dictionary<string, object>();
                customData["stepstarthms"] = resAps["stepstarthms"].ToString();
                customData["stependhms"] = resAps["stependhms"].ToString();
                var ratio=(DateTime.Parse(resAps["stependhms"].ToString()) - DateTime.Parse(resAps["stepstarthms"].ToString())).TotalMinutes ;
                customData["ratio"] = Math.Round((ratio / (24 * 60)),2);//高度占用比
                ratio = (DateTime.Parse(resAps["stepstarthms"].ToString()) - DateTime.Parse(resAps["stepstarthms"].ToString()).Date ).TotalMinutes;
                customData["startPercent"] = Math.Round((ratio / (24 * 60)), 2);//起始位置比
                customData["containername"] = resAps["containername"].ToString();
                customData["workflowstepname"] = resAps["workflowstepname"].ToString();
                period["customData"] = customData;

                periods.Add(period);                
            }

            resApsData["periods"] = periods;

            returnData.Add(resApsData);
        }

        result.ReturnData = JsonConvert.SerializeObject(returnData);
        result.Result = true;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

}